// index.js
// 获取应用实例
const app = getApp()

Page({
  data: {
    background: ['http://resource.mzdpgroup.com/%E5%81%9C%E8%BD%A6%E5%9C%BA2@2x.png', 'http://resource.mzdpgroup.com/%E5%81%9C%E8%BD%A6%E5%9C%BA2@2x.png', 'http://resource.mzdpgroup.com/%E5%81%9C%E8%BD%A6%E5%9C%BA2@2x.png'],
    indicatorColor: 'rgba(0,0,0,.1)',
    indicatorActiveColor: '#3989FF'
  },
  // 事件处理函数
  onLoad() {
  },
  getUserInfo(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  handleActionButtonClick (e) {
    console.log(e.currentTarget.dataset.type)
    // 判断是否登录
    if (!app.globalData.isLogin) {
      this.weChatAuthProcess()
    }
    if (app.globalData.isLogin) {
      if (e.currentTarget.dataset.type === 'scan') {
        this.scanCode()
        // console.log(wx.getStorageSync('uid'))
        // this.getDeviceState()
      }
      if (e.currentTarget.dataset.type === 'order') {
        wx.navigateTo({
          url: '/pages/order/order'
        })
      }
    }


  },
  scanCode () {
    const that = this
    wx.scanCode({
      success(res) {
      console.log(res)
        let codeRes = {}
        if (res.result) {
          codeRes = JSON.parse(res.result)
        }
        if (codeRes.type ==='wash') {
        // 洗车码
          wx.setStorageSync('washId', codeRes.washid)
          wx.setStorageSync('deviceId', codeRes.deviceid)
          that.getDeviceState(codeRes.deviceid)
        }
          // result: "{"type":"wash","washid":"wash16082093616781391","deviceid":"338220100087"}"
      }
    })
  },
  weChatAuthProcess () {
    wx.showModal({
      title: '您还未登录',
      content: '请先登录再进行操作',
      confirm: '立即登录',
      cancel: '暂不登录',
      success (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.navigateTo({
            url: '/pages/getUserPhone/getUserPhone'
          })
        }
      }
    })
  },
  getDeviceState (id) {
    console.log(id)
    app.api.getWashDeviceState({deviceid: id || '338220100087'}).then(res => {
      console.log(res)
      if (!res.resultCode) {
        if (res.data.washing) {
        //  equipment busy
        }
        if (!res.data.washing) {
        // equipment free, judge orders status
          if (res.data.nostarttradno) {
          //  has paid but not started order, begin washing
            app.api.startWach({tradno: res.data.nostarttradno}).then(res => {
              console.log(res)
              if (res.resultCode === 0) {
                wx.navigateTo({
                  url: '/pages/washStatus/washStatus?id=' + id
                })
              }
            })
          }
          if (!res.data.nostarttradno) {
          //  new wash order
            wx.navigateTo({
              url: '/pages/washStatus/washStatus?id=' + id
            })
          }
        }
      }
    })
  }
})
